package com.woniuxy.shop.dao;

import java.util.ArrayList;
import java.util.List;

import com.woniuxy.shop.entity.Address;

/**
*@author 作者：
*version 创建时间：
*类说明：
*/
public class AddressDao {
//	/**
//	 * 根据用户ID查询其地址数量(可以用getUserAllAddress方法代替)
//	 * @param id
//	 * @return
//	 */
//	public int getNumOfAddress(int id){
//		String sql = "select count(*) from user_address where userid=?";
//		return ((Long)DbHelper.executeQueryForScalar(sql, id)).intValue();
//	}
	
	/**
	 * 执行添加地址的sql语句
	 * @param as
	 * @param num
	 * @throws Exception
	 */
	public void addAddress(Address as){
		String sql = "insert into user_address(userid,accepter,telephone,topaddress,detailArea,isDefault) values(?,?,?,?,?,?)";
		Object[] obs = {as.getUserid(),as.getAccepter(),as.getTelephone(),as.getTopaddress(),as.getDetailArea(),as.getIsDefault()};
		DbHelper.excuteSQL(sql,obs); 
	}
	
	/**
	 * 修改指定ID的用户其他地址为非默认
	 * @param userid
	 * @param id
	 */
	public void alterDefaultAddress(int userid,int id) {
		String sql = "update user_address set isDefault='否' where userid=? and id!=?";
		DbHelper.excuteSQL(sql, userid,id);
	}
	
	/**
	 * 根据用户ID查询是否存在该用户
	 * @param id
	 * @return
	 */
	public long queryUserNum(int id) {
		String sql = "select count(*) from user_info where id=?";
		return DbHelper.executeQueryForScalar(sql, id);
	} 
	
	/**
	 * 指定ID删除地址
	 * @param id
	 */
	public void deleteAddress(int id) {
		String sql = "delete from user_address where id=?";
		DbHelper.excuteSQL(sql, id);
	}
	
	/**
	 * 更新地址
	 * @param a
	 */
	public void updateAddress(Address a) {
		String sql = "update user_address set accepter=?, telephone=?, topaddress=?, detailArea=?, isDefault=? where id=?";
		Object[] obs = {a.getAccepter(),a.getTelephone(),a.getTopaddress(),a.getDetailArea(),a.getIsDefault(),a.getId()};
		DbHelper.excuteSQL(sql, obs);
	}
	
	/**
	 * 指定特定ID为默认地址
	 * @param id
	 */
	public void chooseDefaultAddress(int id) {
		String sql = "update user_address set isDefault='是' where id="+id;
		DbHelper.excuteSQL(sql);
	}
	
	/**
	 * 查询某用户所有的地址
	 * @param userid
	 * @return
	 */
	public List<Address> getUserAllAddress(int userid){
		List<Address> addresses = new ArrayList<>();
		String sql = "select * from user_address where userid=?";
		addresses =  DbHelper.executeQuery(sql, Address.class, userid);
		return addresses;
	}
	
	/**
	 * 根据指定ID查询其地址类
	 * @param id
	 * @return
	 */
	public Address getAddressByID(int id) {
		String sql = "select * from user_address where id=?";
		return DbHelper.executeQueryForSingleRow(sql, Address.class,id);
	}
}
